import type { ObjectDirective } from 'vue'
import useClipboard from 'vue-clipboard3'

if (!useClipboard) {
  throw new Error('you should npm install `vue-clipboard3` --save at first ')
}

const { toClipboard } = useClipboard()

/**  点击元素实现复制功能  **/
/**  v-clipboard:copy="需要被复制的内容" **/
/**  v-clipboard:copy.prevent="需要被复制的内容"  将阻止调用默认的成功与失败回调 **/
/**  v-clipboard:success="复制成功后的回调" **/
/**  v-clipboard:error="复制失败后的回调" **/
export const clipboard: ObjectDirective = {
  mounted(el, binding) {
    switch (binding.arg) {
      case 'copy':
        initCopy(binding, el)
        break
      case 'success':
        el.clipSuccess = binding.value
        break
      case 'error':
        el.clipError = binding.value
        break
    }
  },
  updated(el, binding) {
    switch (binding.arg) {
      case 'copy':
        el.clipValue = binding.value
        break
      case 'success':
        el.clipSuccess = binding.value
        break
      case 'error':
        el.clipError = binding.value
        break
    }
  },
  unmounted(el, binding) {
    switch (binding.arg) {
      case 'copy':
        el.removeEventListener('click', el.clipCopy)
        break
      case 'success':
        delete el.clipSuccess
        break
      case 'error':
        delete el.clipError
        break
    }
  }
}

const initCopy = (binding, el) => {
  el.clipValue = binding.value
  const prevent = binding.modifiers.prevent
  el.clipCopy = async () => {
    try {
      const res = await toClipboard(el.clipValue)
      const callBack = prevent
        ? el.clipSuccess
        : el.clipSuccess || defaultSuccess
      callBack && callBack(res)
    } catch (err) {
      const callBack = prevent ? el.clipError : el.clipError || defaultError
      callBack && callBack(err, el.clipValue)
    }
  }
  el.addEventListener('click', el.clipCopy)
}

const defaultSuccess = (res) => {
  window.$message.success(`拷贝${res.text}成功`)
}

const defaultError = (err, content) => {
  console.log(err)
  window.$message.error(`拷贝${content}失败`)
}
